package cn.com.connext.scrm.service;

import cn.com.connext.scrm.domain.master.*;
import cn.com.connext.scrm.repository.master.*;
import cn.com.connext.scrm.service.dto.CardCouponDto;
import cn.com.connext.scrm.service.mapper.ClickCountService;
import cn.com.connext.scrm.service.mapper.OrderService;
import cn.com.connext.scrm.web.rest.enums.CardCouponNature;
import cn.com.connext.scrm.web.rest.enums.CardCouponSource;
import cn.com.connext.scrm.web.rest.vm.CardCouponAddressVM;
import cn.com.connext.scrm.web.rest.vm.CardCouponDetailVM;
import cn.com.connext.scrm.web.rest.vm.QueryCardCouponVM;
import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.Predicate;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Transactional
public class CardCouponService {

    private static final Logger log = LoggerFactory.getLogger(CardCouponService.class);

    @Autowired
    private PrizeRepository prizeRepository;

    @Autowired
    private PrizeExtRepository prizeExtRepository;

    @Autowired
    private PrizeGoodRepository prizeGoodRepository;

    @Autowired
    private OrderRepository orderRepository;

    @Autowired
    private ProductRepository productRepository;

    @Autowired
    private DwaConvertCodeRepository dwaConvertCodeRepository;

    @Autowired
    private DwaGetCouponRepository dwaGetCouponRepository;

    @Autowired
    private ClickCountService clickCountService;

    @Autowired
    private OrderService orderService;

    @Autowired
    private CouponRepository couponRepository;


    @Autowired
    private DrawActivityRepository drawActivityRepository;
    /**
     * 查询卡券列表
     *
     * @param vm
     * @return
     */
    public List<CardCouponDto> list(QueryCardCouponVM vm) {
        log.info("查询卡券列表，参数：{}", JSON.toJSONString(vm));
        final String unionId = vm.getUnionId();
        if (!StringUtils.hasText(unionId)) {
            return Collections.emptyList();
        }
        // 放在要检测的代码段前，取开始前的时间戳
        Long startTime = System.currentTimeMillis();

        List<CardCouponDto> list = new ArrayList<>();

        Long defaultStartTime = System.currentTimeMillis();
        //默认两条入会优惠券
        List<CardCouponDto> defaultList = listDefault(vm);
        Long defaultEndTime = System.currentTimeMillis();
        log.info("#####################入会卷执行时间"+ (defaultEndTime-defaultStartTime));
        list.addAll(defaultList);

        Long prizeGoodsStartTime = System.currentTimeMillis();
        // 奖品
        List<CardCouponDto> prizeGoods = listPrizeGood(vm);
        // 放在要检测的代码段后，取结束后的时间戳
        Long prizeGoodsEndTime = System.currentTimeMillis();
        log.info("#####################奖品查询执行时间"+ (prizeGoodsEndTime-prizeGoodsStartTime));
        list.addAll(prizeGoods);

        Long productsStartTime = System.currentTimeMillis();
        // 积分产品
        List<CardCouponDto> products = listProduct(vm);
        // 放在要检测的代码段后，取结束后的时间戳
        Long productsEndTime = System.currentTimeMillis();
        log.info("#####################积分产品执行时间"+ (productsEndTime-productsStartTime));
        list.addAll(products);

        Long packagesStartTime = System.currentTimeMillis();
        // 组合券包
        List<CardCouponDto> packages = listPackage(vm);
        // 放在要检测的代码段后，取结束后的时间戳
        Long packagesEndTime = System.currentTimeMillis();
        log.info("#####################组合卷执行时间"+ (packagesEndTime-packagesStartTime));

        list.addAll(packages);
        Long EndTime = System.currentTimeMillis();
        log.info("#####################查询列表总耗时"+ (EndTime-startTime));
        log.info("查询卡券列表，结果：{}", JSON.toJSONString(list.stream().map(CardCouponDto::getCardCouponId).collect(Collectors.toList())));
        log.info("查询卡券列表，结果：{}", JSON.toJSONString(list.stream().map(CardCouponDto::getCardCouponName).collect(Collectors.toList())));
        return list;
    }

    /*
     * 查询奖品
     */
    private List<CardCouponDto> listPrizeGood(QueryCardCouponVM vm) {
        final String unionId = vm.getUnionId();
        if (!StringUtils.hasText(unionId)) {
            return Collections.emptyList();
        }

        // 1. 查询用户中奖记录
        List<Prize> prizes = prizeRepository.findUnionId(unionId);
        List<Integer> goodIds = prizes.stream().map(Prize::getGoodId).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(goodIds)) {
            return Collections.emptyList();
        }

        // 2. 查询奖品
        Specification<PrizeGood> prizeGoodSpecification = (root, query, criteriaBuilder) -> {
            List<Predicate> predicates = new ArrayList<>();
            // 奖品ID
            CriteriaBuilder.In<Object> goodIdPredicate = criteriaBuilder.in(root.get("id"));
            goodIds.forEach(goodIdPredicate::value);
            predicates.add(goodIdPredicate);
            // 卡券性质
            if (StringUtils.hasText(vm.getCouponNature())) {
                Predicate couponNaturePredicate = criteriaBuilder.equal(root.get("couponNature"), vm.getCouponNature());
                predicates.add(couponNaturePredicate);
            } else {
                // 卡券性质为空的，两种都查
                CriteriaBuilder.In<Object> couponNaturePredicate = criteriaBuilder.in(root.get("couponNature"));
                couponNaturePredicate.value(CardCouponNature.ACTIVITY.getCode());
                couponNaturePredicate.value(CardCouponNature.DISCOUNT.getCode());
                predicates.add(criteriaBuilder.and(couponNaturePredicate));
            }
            return criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()]));
        };

        List<PrizeGood> list = prizeGoodRepository.findAll(prizeGoodSpecification);
        Map<Integer, PrizeGood> prizeGoodMap = list.stream().collect(Collectors.toMap(PrizeGood::getId, prizeGood -> prizeGood));
//        Map<Integer, Integer> prizeIdMap = prizes.stream().collect(Collectors.toMap(Prize::getGoodId, Prize::getId, (id1, id2) -> id2));
//        Map<Integer, Prize> prizeObjMap = prizes.stream().collect(Collectors.toMap(Prize::getGoodId, prize -> prize, (id1, id2) -> id2));
        List<Integer> prizeIds = prizes.stream().map(Prize::getId).collect(Collectors.toList());
        List<PrizeExt> prizeExts = prizeExtRepository.getListByPrizeIds(prizeIds);
        Map<Integer, PrizeExt> prizeExtMap = prizeExts.stream().collect(Collectors.toMap(PrizeExt::getPrizeId, prizeExt -> prizeExt));
        //优化订单查询
        List<OrderRecord> orderByUserId = orderService.findOrderByUserId(unionId);
        Map<String, OrderRecord> orderRecordMap = new HashMap<>();
        orderByUserId.stream().forEach(orderRecord -> {
            orderRecordMap.put(unionId+orderRecord.getProductId()+orderRecord.getPrizeId(),orderRecord);
        });
        return prizes.stream()
            .filter(prize -> null!= prizeGoodMap.get(prize.getGoodId()) )
            .map(prize -> {
            // 地址
                PrizeExt prizeExt = prizeExtMap.get(prize.getId());
                PrizeGood prizeGood = prizeGoodMap.get(prize.getGoodId());
                CardCouponDto cardCoupon = toCardCouponDto(prizeGood, prizeExt);
                cardCoupon.setPrizeId(prize.getId());
                // 查询订单号
                OrderRecord orderRecord = orderRecordMap.get(unionId + prizeGood.getId() + prize.getId());
                if (null != orderRecord) {
                    cardCoupon.setOrderCode(orderRecord.getOrderCode());
                    cardCoupon.setAddress(orderRecord.getAddress());
                    cardCoupon.setMobile(orderRecord.getMobile());
                    cardCoupon.setName(orderRecord.getName());
                }
//                List<OrderRecord> orders = orderService.getOrderOneByCarRollPrizeId(unionId, prizeGood.getId().toString(),prize.getId());
//                orders.stream().findFirst().ifPresent(order ->
//                    {
//                        cardCoupon.setOrderCode(order.getOrderCode());
//                        cardCoupon.setAddress(order.getAddress());
//                        cardCoupon.setMobile(order.getMobile());
//                        cardCoupon.setName(order.getName());
//                    }
//                );
                return cardCoupon;
            }).collect(Collectors.toList());


//        return list.stream()
//            .map(prizeGood -> {
//                // 地址
//                List<PrizeExt> prizeExts = prizeExtRepository.findByPrizeId(prizeIdMap.get(prizeGood.getId()));
//                PrizeExt prizeExt = prizeExts.stream().findFirst().orElse(null);
//
//                CardCouponDto cardCoupon = toCardCouponDto(prizeGood, prizeExt);
//                //补充一部分信息 210903
//                cardCoupon.setPrizeId(prizeIdMap.get(prizeGood.getId()));
////                Prize prizeobj = prizeObjMap.get(prizeGood.getId());
////                if (null != prizeobj) {
////                    cardCoupon.setQrCodeId(prizeobj.getBeScanCode());
////                    cardCoupon.setStockId(prizeobj.getStockId());
////                    cardCoupon.setCouponId(prizeobj.getCouponId());
////                    cardCoupon.setVerifyStatus(prizeobj.getVerifyStatus());
////                    DrawActivity activity = drawActivityRepository.findOne(prizeobj.getActivityId());
////                    if (activity != null) {
////                        cardCoupon.setActivityType(activity.getActivityType());
////                    }
////                }
//                // 查询订单号
//                List<OrderRecord> orders = orderService.getOrderOneByCarRoll(unionId, prizeGood.getId().toString());
//                orders.stream().findFirst().ifPresent(order ->
//                    {
//                        cardCoupon.setOrderCode(order.getOrderCode());
//                        cardCoupon.setAddress(order.getAddress());
//                        cardCoupon.setMobile(order.getMobile());
//                        cardCoupon.setName(order.getName());
//                    }
//                );
//                return cardCoupon;
//            })
//            .collect(Collectors.toList());
    }

    /*
     * 查询积分产品
     */
    private List<CardCouponDto> listProduct(QueryCardCouponVM vm) {
        final String unionId = vm.getUnionId();
        if (!StringUtils.hasText(unionId)) {
            return Collections.emptyList();
        }
        // 1. 查询用户兑换记录
        List<OrderRecord> orderRecords = orderRepository.findOrderRecordsByUserId(unionId);
        List<String> productIds = orderRecords.stream().map(OrderRecord::getProductId).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(productIds)) {
            return Collections.emptyList();
        }

        // 2. 查询产品
        Specification<Product> productSpecification = (root, query, criteriaBuilder) -> {
            List<Predicate> predicates = new ArrayList<>();
            // 产品ID
            CriteriaBuilder.In<Object> productIdPredicate = criteriaBuilder.in(root.get("id"));
            productIds.forEach(productIdPredicate::value);
            predicates.add(productIdPredicate);
            // 卡券性质
            if (StringUtils.hasText(vm.getCouponNature())) {
                Predicate couponNaturePredicate = criteriaBuilder.equal(root.get("couponNature"), vm.getCouponNature());
                predicates.add(couponNaturePredicate);
            } else {
                // 卡券性质为空的，两种都查
                CriteriaBuilder.In<Object> couponNaturePredicate = criteriaBuilder.in(root.get("couponNature"));
                couponNaturePredicate.value(CardCouponNature.ACTIVITY.getCode());
                couponNaturePredicate.value(CardCouponNature.DISCOUNT.getCode());
                predicates.add(criteriaBuilder.and(couponNaturePredicate));
            }
            return criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()]));
        };

        List<Product> list = productRepository.findAll(productSpecification);
        return list.stream().map(product -> {
            OrderRecord orderRecord = orderRecords.stream()
                .filter(record -> product.getId().equals(record.getProductId()))
                .findFirst()
                .orElseGet(OrderRecord::new);
            return toCardCouponDto(product, orderRecord);
        }).collect(Collectors.toList());
    }

    /*
     * 查询组合券包
     */
    private List<CardCouponDto> listPackage(QueryCardCouponVM vm) {
        final String unionId = vm.getUnionId();
        if (!StringUtils.hasText(unionId)) {
            return Collections.emptyList();
        }

        // 1. 查询组合券包（组合券包属于优惠券）
        if (!StringUtils.hasText(vm.getCouponNature()) || CardCouponNature.DISCOUNT.getCode().equals(vm.getCouponNature())) {
            List<DwaGetCoupon> list = dwaGetCouponRepository.findListByUnionId(unionId);
            return list.stream()
                .map(DwaGetCoupon::getActivityId)
                .distinct()
                .map(activityId -> {
                    DwaGetCoupon dwaGetCoupon = new DwaGetCoupon();
                    dwaGetCoupon.setActivityId(activityId);
                    dwaGetCoupon.setUnionId(unionId);
                    return toCardCouponDto(dwaGetCoupon, null, null);
                }).collect(Collectors.toList());
        } else {
            return Collections.emptyList();
        }
    }

    /**
     * 查询详情
     *
     * @param vm
     * @return
     */
    public CardCouponDto detail(CardCouponDetailVM vm) {
        log.info("查询卡券详情，参数：{}", JSON.toJSONString(vm));
        final CardCouponSource cardCouponSource = CardCouponSource.getByCode(vm.getCardCouponSource());
        Assert.hasText(vm.getUnionId(), "用户ID不能为空！");
        Assert.hasText(vm.getCardCouponId(), "卡券ID不能为空！");
        Assert.notNull(cardCouponSource, "未知的卡券来源：" + vm.getCardCouponSource());

        CardCouponDto cardCoupon = null;
        switch (cardCouponSource) {
            case PRIZE_GOOD:
                cardCoupon = detailPrizeGood(vm);
                break;
            case PRODUCT:
                cardCoupon = detailProduct(vm);
                break;
            case ACTIVITY:
                cardCoupon = detailPackage(vm);
                break;
        }
        log.info("查询卡券详情，结果：{}", JSON.toJSONString(cardCoupon));
        return cardCoupon;
    }

    /*
     * 奖品详情
     */
    private CardCouponDto detailPrizeGood(CardCouponDetailVM vm) {
        final String unionId = vm.getUnionId();
        final String cardCouponId = vm.getCardCouponId();

        // 奖品
        PrizeGood prizeGood = prizeGoodRepository.findOne(Integer.valueOf(cardCouponId));
        Assert.notNull(prizeGood, "id为" + cardCouponId + "的奖品不存在！");
        // 中奖记录
        List<Prize> prizes = prizeRepository.findByUnionIdAndGoodId(unionId, prizeGood.getId());
        Assert.notEmpty(prizes, "奖品id[" + cardCouponId + "]，未获取到当前用户的中奖记录！");
        // 地址
        List<PrizeExt> prizeExts = prizeExtRepository.findByPrizeId(prizes.stream().findFirst().get().getId());
        PrizeExt prizeExt = prizeExts.stream().findFirst().orElse(null);

        CardCouponDto cardCoupon = toCardCouponDto(prizeGood, prizeExt);

        // 查询订单号
        List<OrderRecord> orders = orderService.getOrderOneByCarRoll(unionId, cardCouponId);
        orders.stream().findFirst().ifPresent(order -> cardCoupon.setOrderCode(order.getOrderCode()));
        return cardCoupon;
    }

    /*
     * 积分产品详情
     */
    private CardCouponDto detailProduct(CardCouponDetailVM vm) {
        final String unionId = vm.getUnionId();
        final String cardCouponId = vm.getCardCouponId();
        // 查询积分产品
        Product product = productRepository.findById(cardCouponId);
        // 查询对应订单
        List<OrderRecord> orderRecords = orderRepository.findOrderRecordsByUserId(unionId);
        OrderRecord orderRecord = orderRecords.stream()
            .filter(order -> order.getProductId().equals(product.getId()))
            .findFirst()
            .orElse(null);
        return toCardCouponDto(product, orderRecord);
    }

    /*
     * 组合券包详情
     */
    private CardCouponDto detailPackage(CardCouponDetailVM vm) {
        final String unionId = vm.getUnionId();
        final String cardCouponId = vm.getCardCouponId();

        List<DwaGetCoupon> dwaGetCoupons = dwaGetCouponRepository.findListByUnionId(unionId);
        Assert.notEmpty(dwaGetCoupons, "未查到当前用户的券包内卡券！");
        dwaGetCoupons = dwaGetCoupons.stream()
            .filter(coupon -> cardCouponId.equals(coupon.getActivityId()))
            .collect(Collectors.toList());
        Assert.notEmpty(dwaGetCoupons, "未查到当前用户活动id为" + cardCouponId + "的券包内卡券！");
        DwaGetCoupon group = dwaGetCoupons.stream().findFirst().orElse(null);

        DwaConvertCode dwaConvertCode = dwaConvertCodeRepository.findByUnionId(unionId);
        Assert.notNull(dwaConvertCode, "未查到当前用户的券包！");

        // 券包内卡券
        List<Integer> goodIds = dwaGetCoupons.stream().map(DwaGetCoupon::getGoodId).collect(Collectors.toList());
        List<CardCouponDto> items = new ArrayList<>();
        for (Integer goodId : goodIds) {
            // 查询奖品
            PrizeGood prizeGood = prizeGoodRepository.findOne(goodId);
            if (prizeGood == null) {
                log.error("goodId为" + goodId + "的奖品不存在！");
                continue;
            }

            // 查询地址
            PrizeExt prizeExt = null;
            List<Prize> prizes = prizeRepository.findByUnionIdAndGoodId(unionId, goodId);
            if (!CollectionUtils.isEmpty(prizes)) {
                List<PrizeExt> prizeExts = prizeExtRepository.findByPrizeId(prizes.stream().findFirst().get().getId());
                prizeExt = prizeExts.stream().findFirst().orElse(null);
            }
            CardCouponDto cardCoupon = toCardCouponDto(prizeGood, prizeExt);
            // 查询订单号
            List<OrderRecord> orders = orderService.getOrderOneByCarRoll(unionId, prizeGood.getId().toString());
            orders.stream().findFirst().ifPresent(order -> cardCoupon.setOrderCode(order.getOrderCode()));
            items.add(cardCoupon);
        }

        // 次数？（根据用户id查询活动信息）
        ClickCount entity = clickCountService.findByActivityIdAndUnionId(cardCouponId, unionId);
        int count = entity != null ? entity.getCount() : 0;

        CardCouponDto cardCouponDto = toCardCouponDto(group, dwaConvertCode, items);
        cardCouponDto.setClickCount(count);
        return cardCouponDto;
    }

    /*
     * 奖品 -> 卡券
     */
    private CardCouponDto toCardCouponDto(PrizeGood prizeGood, PrizeExt prizeExt) {
        if (prizeGood == null) {
            return null;
        }
        CardCouponDto cardCoupon = new CardCouponDto();
        cardCoupon.setCardCouponId(prizeGood.getId().toString());
        cardCoupon.setCardCouponSource(CardCouponSource.PRIZE_GOOD.getCode());
        cardCoupon.setCouponNature(prizeGood.getCouponNature());
        cardCoupon.setCardCouponName(prizeGood.getGoodName());
        cardCoupon.setType(Objects.toString(prizeGood.getType(), null));
        cardCoupon.setCouponType(prizeGood.getCouponType());
        cardCoupon.setCardId(prizeGood.getCardId());
        cardCoupon.setRedeemCode(prizeGood.getGoodCode());
        cardCoupon.setImage(prizeGood.getGoodImg());
        cardCoupon.setDescription(prizeGood.getRemark());
        cardCoupon.setLink(prizeGood.getPagePath());
        cardCoupon.setStartTime(prizeGood.getExpireStartDate());
        cardCoupon.setEndTime(prizeGood.getExpireDate());
        cardCoupon.setHxContent1(prizeGood.getHxContent1());
        cardCoupon.setHxContent2(prizeGood.getHxContent2());

        cardCoupon.setMgmButtonName(prizeGood.getMgmButtonName());
        cardCoupon.setMgmStatus(prizeGood.getMgmStatus());
        cardCoupon.setMgmUrl(prizeGood.getMgmUrl());
        //添加appid 按钮名称 zyl
        cardCoupon.setAppId(prizeGood.getAppId());
        cardCoupon.setButtonText(prizeGood.getButtonText());
        cardCoupon.setPathType(prizeGood.getPathType());
        // 地址
        if (prizeExt != null) {
            cardCoupon.setName(prizeExt.getName());
            cardCoupon.setMobile(prizeExt.getMobile());
            cardCoupon.setAddress(prizeExt.getAddress());
        }
        return cardCoupon;
    }

    /*
     * 积分产品 -> 卡券
     */
    private CardCouponDto toCardCouponDto(Product product, OrderRecord orderRecord) {
        if (product == null) {
            return null;
        }
        CardCouponDto cardCoupon = new CardCouponDto();
        cardCoupon.setCardCouponId(product.getId());
        cardCoupon.setCardCouponSource(CardCouponSource.PRODUCT.getCode());
        cardCoupon.setCouponNature(product.getCouponNature());
        cardCoupon.setCardCouponName(product.getName());
        cardCoupon.setType(Objects.toString(product.getType(), null));
        cardCoupon.setCardId(product.getCouponId());
        cardCoupon.setRedeemCode(product.getGoodCode());
        cardCoupon.setImage(product.getDetailImage());
        cardCoupon.setDescription(product.getDescription());
        cardCoupon.setLink(product.getUrl());
        cardCoupon.setStartTime(product.getStartTime());
        cardCoupon.setEndTime(product.getEndTime());

        // 地址
        if (orderRecord != null) {
            cardCoupon.setName(orderRecord.getName());
            cardCoupon.setMobile(orderRecord.getMobile());
            cardCoupon.setAddress(orderRecord.getAddress());
        }
        return cardCoupon;
    }

    /*
     * 组合券包 -> 卡券
     */
    private CardCouponDto toCardCouponDto(DwaGetCoupon group, DwaConvertCode dwaConvertCode, List<CardCouponDto> items) {
        if (group == null) {
            return null;
        }
        CardCouponDto cardCoupon = new CardCouponDto();
        cardCoupon.setCardCouponId(group.getActivityId());
        cardCoupon.setCardCouponSource(CardCouponSource.ACTIVITY.getCode());
        cardCoupon.setCouponNature(CardCouponNature.DISCOUNT.getCode()); // 组合券包属于优惠券
        cardCoupon.setCardCouponName("组合券包");
        // 组合券包码
        if (dwaConvertCode != null) {
            cardCoupon.setRedeemCode(dwaConvertCode.getCode());
        }
        // 组合券包下的奖品
        if (!CollectionUtils.isEmpty(items)) {
            cardCoupon.setItems(items);
        }
        return cardCoupon;
    }

    /**
     * 新增、更新卡券地址
     *
     * @param vm
     */
    public void address(CardCouponAddressVM vm) {
        final String unionId = vm.getUnionId();
        final String cardCouponId = vm.getCardCouponId();
        Assert.hasText(unionId, "用户ID不能为空！");
        Assert.hasText(cardCouponId, "卡券ID不能为空！");
        Integer prizeId;

        if (null!= vm.getPrizeId()) {
            prizeId = vm.getPrizeId();
        } else {
            // 中奖记录
            List<Prize> prizes = prizeRepository.findByUnionIdAndGoodId(unionId, Integer.valueOf(cardCouponId));
            Assert.notEmpty(prizes, "奖品id[" + cardCouponId + "]，未获取到当前用户的中奖记录！");

            // 查询原有地址
            prizeId = prizes.stream().findFirst().get().getId();
        }

        List<PrizeExt> prizeExts = prizeExtRepository.findByPrizeId(prizeId);

        // 新增或更新
        PrizeExt prizeExt;
        if (CollectionUtils.isEmpty(prizeExts)) {
            prizeExt = new PrizeExt();
            prizeExt.setCreateTime(new Date());
            prizeExt.setUpdateTime(prizeExt.getCreateTime());
        } else {
            prizeExt = prizeExts.stream().findFirst().get();
            prizeExt.setUpdateTime(new Date());
        }

        prizeExt.setPrizeId(prizeId);
        prizeExt.setName(vm.getName());
        prizeExt.setMobile(vm.getMobile());
        prizeExt.setAddress(vm.getAddress());
        prizeExtRepository.save(prizeExt);
    }
    public List<CardCouponDto> listDefault(QueryCardCouponVM vm) {
        List<CardCouponDto> list = new ArrayList<>();
        // 卡券性质
        if (StringUtils.isEmpty(vm.getCouponNature()) || "2".equals(vm.getCouponNature())) {
            //查询两张默认优惠券
            List<OrderRecord> orderList = orderRepository.findNoWechatOrderByUserId(vm.getUnionId());
            if (!CollectionUtils.isEmpty(orderList)) {
                orderList.forEach(c -> {
                    if (StringUtils.isEmpty(c.getProductId())) {
                        if (c.getCouponId().compareTo("9333557") == 0 || c.getCouponId().compareTo("9557455") == 0) {
                            List<Coupon> coupons = couponRepository.findByCouponId(c.getCouponId());
                            if (!CollectionUtils.isEmpty(coupons)) {
                                Coupon coupon = coupons.get(0);
                                CardCouponDto newCard = new CardCouponDto();
                                newCard.setCardCouponName(coupon.getCouponName());
                                newCard.setImage("https://wxadmin.singlemalts.com.cn/group1/M00/01/94/rBOeiF77BRKAc3i9AAAI-Qs5Cjk356_640x10000.jpg");
                                newCard.setType(c.getType()+"");
                                newCard.setCardCouponSource(CardCouponSource.PRODUCT.getCode());
                                newCard.setLink(coupon.getUrl());
                                newCard.setCardCouponId(coupon.getCouponId());
                                newCard.setDefaultFlag("1");
                                list.add(newCard);
                            }
                        }
                    }
                });
            }
        }
        return list;
    }
}
